﻿@{
    ViewBag.Title = "开票通知单";
    Layout = null;
}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>修改开票通知单</title>
    <!-- 引用Layui的CSS -->
    <link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
    <style>
        /* 整体表单容器样式 */
        .order-form-container {
            padding: 15px;
        }
        /* 表单行样式 */
        .layui-form-item {
            margin-bottom: 15px;
        }
        /* 操作按钮容器样式 */
        .operation-buttons {
            text-align: right;
            margin-bottom: 15px;
        }
        /* 表格样式 */
        .layui-table {
            width: 100%;
            margin-top: 15px;
        }
            /* 表格中的输入框样式 */
            .layui-table td .layui-input {
                border: 1px solid #e6e6e6;
            }
        /* 选择物料按钮样式 */
        .selectMaterialButton {
            margin-left: 5px;
        }
    </style>
</head>

<body>
    <div class="order-form-container">
        <!-- 操作按钮 -->
        <div class="operation-buttons">
            <button class="layui-btn layui-btn-normal" id="saveButton">保存修改</button>
        </div>

        <!-- 基本信息表单 -->
        <form class="layui-form" action="">
            <div class="layui-form-item layui-row layui-col-space15">
                <div class="layui-col-md3">
                    <label class="layui-form-label">单据编码</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input" placeholder="单据编码自动生成" id="documentCode" readonly>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">业务类型</label>
                    <div class="layui-input-block">
                        <select  id="businessType" lay-verify="required">
                            <option value="销售开票">销售开票</option>
                            <option value="采购开票">采购开票</option>
                        </select>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">客户名称</label>
                    <div class="layui-input-block">
                        <input type="text"  id="customerName" class="layui-input" lay-verify="required">
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">开户行</label>
                    <div class="layui-input-block">
                        <input type="text"  id="bank" class="layui-input">
                    </div>
                </div>
            </div>

            <div class="layui-form-item layui-row layui-col-space15">
                <div class="layui-col-md3">
                    <label class="layui-form-label">单据日期</label>
                    <div class="layui-input-block">
                        <input type="date"  id="documentDate" class="layui-input" lay-verify="required">
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">操作员</label>
                    <div class="layui-input-block">
                        <input type="text" id="operator" class="layui-input" readonly>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">蓝字红字</label>
                    <div class="layui-input-block">
                        <select  id="invoiceTypeFlag" lay-verify="required">
                            <option value="蓝字">蓝字</option>
                            <option value="红字">红字</option>
                        </select>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">账号</label>
                    <div class="layui-input-block">
                        <input type="text" id="accountNumber" class="layui-input">
                    </div>
                </div>
            </div>

            <div class="layui-form-item layui-row layui-col-space15">
                <div class="layui-col-md3">
                    <label class="layui-form-label">单据状态</label>
                    <div class="layui-input-block">
                        <select id="documentStatus" lay-verify="required">
                            <option value="开立">开立</option>
                            <option value="审核">审核</option>
                            <option value="已开票">已开票</option>
                        </select>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">审核员</label>
                    <div class="layui-input-block">
                        <input type="text"  id="auditor" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">税率</label>
                    <div class="layui-input-block">
                        <select  id="taxRate" lay-verify="required">
                            <option value="13%">13%</option>
                            <option value="9%">9%</option>
                            <option value="6%">6%</option>
                            <option value="3%">3%</option>
                            <option value="0%">0%</option>
                            <option value="无">无</option>
                        </select>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">税号</label>
                    <div class="layui-input-block">
                        <input type="text"  id="taxNumber" class="layui-input" lay-verify="required">
                    </div>
                </div>
            </div>

            <div class="layui-form-item layui-row layui-col-space15">
                <div class="layui-col-md3">
                    <label class="layui-form-label">业务状态</label>
                    <div class="layui-input-block">
                        <select  id="businessStatus" lay-verify="required">
                            <option value="正常">正常</option>
                            <option value="手工关闭">手工关闭</option>
                            <option value="系统关闭">系统关闭</option>
                        </select>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">审核日期</label>
                    <div class="layui-input-block">
                        <input type="date"  id="auditDate" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">发票类型</label>
                    <div class="layui-input-block">
                        <select  id="invoiceType" lay-verify="required">
                            <option value="">请选择</option>
                            <optgroup label="增值税发票管理系统">
                                <option value="专用发票">增值税专用发票</option>
                                <option value="电子专用发票">增值税电子专用发票</option>
                                <option value="普通发票">增值税普通发票</option>
                            </optgroup>
                            <optgroup label="其他发票类型">
                                <option value="电子普通发票">增值税电子普通发票</option>
                                <option value="卷式普通发票">增值税普通发票(卷式)</option>
                                <option value="通行费发票">通行费发票</option>
                            </optgroup>
                        </select>
                    </div>
                </div>
                <div class="layui-col-md3">
                    <label class="layui-form-label">地址电话</label>
                    <div class="layui-input-block">
                        <input type="text"  id="addressPhone" class="layui-input">
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">交付邮箱</label>
                <div class="layui-input-block">
                    <input type="email" id="deliveryEmail" class="layui-input" placeholder="请输入交付邮箱">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">备注信息</label>
                <div class="layui-input-block">
                    <textarea  id="remark" class="layui-textarea" placeholder="请输入备注信息"></textarea>
                </div>
            </div>
        </form>

        <!-- 物料信息表格 -->
        <div class="layui-form-item">
            <button class="layui-btn layui-btn-sm" id="addMaterialButton">
                <i class="layui-icon">&#xe654;</i> 新增物料
            </button>
        </div>

        <table class="layui-table" id="materialTable">
            <thead>
                <tr>
                    <th width="40">序号</th>
                    <th width="180">物料编码</th>
                    <th width="150">物料名称</th>
                    <th width="120">型号规格</th>
                    <th width="80">主计量</th>
                    <th width="80">数量</th>
                    <th width="100">单价</th>
                    <th width="100">金额</th>
                    <th width="120">质量要求</th>
                    <th width="120">包装要求</th>
                    <th width="120">备注</th>
                    <th width="80">操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- 动态添加行 -->
            </tbody>
        </table>
    </div>

    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
    <script>
        layui.use(['layer', 'form', 'jquery'], function () {
            var layer = layui.layer;
            var form = layui.form;
            var $ = layui.jquery;

            // 从URL获取ID参数
            function getQueryParam(name) {
                const params = new URLSearchParams(window.location.search);
                return params.get(name);
            }

            // 页面加载时根据ID查询数据
            $(function () {
                const id = getQueryParam('id');
                if (id) {
                    loadInvoiceData(id);
                } else {
                    layer.msg('未获取到单据ID', { icon: 2 });
                }
            });

            // 加载数据 - 修正URL格式
            function loadInvoiceData(id) {
                const loadIndex = layer.load(2, { shade: 0.3 });
                $.ajax({
                    // url: `http://localhost:5234/api/Procurements/FanTianInvoiceSettlementEntityALL?InvoiceSettlementEntityId=${id}`,
                    url: `@ViewBag.BaseUrl/T7/Procurements/FanTianInvoiceSettlementEntityALL?InvoiceSettlementEntityId=${id}`,
                    type: 'GET',
                    dataType: 'json',
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.code === 210 && res.data?.length > 0) {
                            fillFormData(res.data[0]);
                        } else {
                            layer.msg(res.msg || '数据加载失败', { icon: 2 });
                        }
                    },
                    error: function (xhr) {
                        layer.close(loadIndex);
                        layer.msg(`请求失败: ${xhr.statusText}`, { icon: 2 });
                        console.error('请求详情:', {
                            url: xhr.responseURL,
                            status: xhr.status,
                            response: xhr.responseText
                        });
                    }
                });
            }

            // 填充表单 - 增强健壮性
            function fillFormData(data) {
                try {
                    // 主表单数据
                    const fields = {
                        documentCode: data.documentCode,
                        businessType: data.businessType,
                        customerName: data.customerName,
                        bank: data.bank,
                        deliveryEmail: data.deliveryEmail,
                        documentDate: data.documentDate?.split('T')[0],
                        operator: data.operator,
                        invoiceTypeFlag: data.invoiceTypeFlag,
                        accountNumber: data.accountNumber,
                        remark: data.remark,
                        documentStatus: data.documentStatus,
                        auditor: data.auditor,
                        taxRate: data.taxRate,
                        taxNumber: data.taxNumber,
                        businessStatus: data.businessStatus,
                        auditDate: data.auditDate?.split('T')[0],
                        invoiceType: data.invoiceType,
                        addressPhone: data.addressPhone,

                        materialsCode: data.materialsCode,
                        materialsName: data.materialsName,
                        modelSpecification: data.modelSpecification,
                        calulate: data.calulate,
                        calulateNumber: data.calulateNumber,
                        price: data.price,
                        totalPrice: data.totalPrice,
                        qualityRequir: data.qualityRequir,
                        packRequir: data.packRequir,
                        remark: data.remark
                    };

                    // 设置表单值
                    Object.entries(fields).forEach(([key, value]) => {
                        const $elem = $(`#${key}`);
                        if ($elem.is('select')) {
                            $elem.val(value || '').trigger('change');
                        } else {
                            $elem.val(value || '');
                        }
                    });

                    form.render();
                } catch (e) {
                    console.error('填充数据出错:', e);
                    layer.msg('数据加载失败，请检查控制台', { icon: 2 });
                }
            }



            // 初始化一个空行
            function initEmptyRow() {
                return {
                    materialsCode: '',
                    materialsName: '张靖威的物料',
                    modelSpecification: '',
                    color: '',
                    calulate: '',
                    calulateNumber: 0,
                    outBoundNumber: 0,
                    volume: 0,
                    batch: '',
                    price: 0,
                    totalPrice: 0,
                    qualityRequir: '',
                    packRequir: '',
                    remark: '无',
                    materialsClass: 6
                };
            }

            // 添加物料行
            function addMaterialRow(material) {
                material = material || initEmptyRow();
                var rowCount = $('#materialTable tbody tr').length + 1;

                var rowHtml = `
                                                        <tr data-index="${rowCount - 1}">
                                                            <td>${rowCount}</td>
                                                            <td>
                                                                        <input type="text" class="layui-input materialsCode" value="${material.materialsCode}" id="materialsCode" placeholder="物料编码" >
                                                                <button type="button" class="layui-btn layui-btn-xs selectMaterialButton">选择</button>
                                                            </td>
                                                                    <td><input type="text" class="layui-input materialsName" value="${material.materialsName}" id="materialsName" placeholder="物料名称" readonly></td>
                                                                                            <td><input type="text" class="layui-input modelSpecification" value="${material.modelSpecification}" id="modelSpecification" placeholder="型号规格"></td>
                                                            <td>
                                                                        <select class="layui-select calulate" id="calulate">
                                                                    <option value="台" ${material.calulate === '台' ? 'selected' : ''}>台</option>
                                                                 <option value="箱" ${material.calulate === '箱' ? 'selected' : ''}>箱</option>
                                                                 <option value="件" ${material.calulate === '件' ? 'selected' : ''}>件</option>
                                                                </select>
                                                            </td>
                                                                    <td><input type="number" class="layui-input calulateNumber" id="calulateNumber" value="${material.calulateNumber}" placeholder="数量"></td>
                                                                    <td><input type="number" class="layui-input price" id="price" value="${material.price}" placeholder="单价"></td>
                                                                    <td><input type="number" class="layui-input totalPrice" id="totalPrice" value="${material.totalPrice}" placeholder="金额" readonly></td>
                                                                    <td><input type="text" class="layui-input qualityRequir" id="qualityRequir" value="${material.qualityRequir}" placeholder="质量要求"></td>
                                                                    <td><input type="text" class="layui-input packRequir" id="packRequir" value="${material.packRequir}" placeholder="包装要求"></td>
                                                                    <td><input type="text" class="layui-input remark" id="remark" value="${material.remark}" placeholder="备注"></td>
                                                            <td><button type="button" class="layui-btn layui-btn-xs layui-btn-danger deleteMaterialButton">删除</button></td>
                                                        </tr>`;

                $('#materialTable tbody').append(rowHtml);
                form.render();
            }

            // 初始化一个空行
            addMaterialRow();

            // 新增物料按钮点击事件
            $('#addMaterialButton').click(function () {
                addMaterialRow();
            });

            $(document).ready(function () {
                $('.selectMaterialButton').click(function () {
                    // 生成一个介于最小值和最大值之间的随机数，这里模拟long类型范围
                    const min = Math.pow(10, 18); // 示例最小值
                    const max = Math.pow(10, 19) - 1; // 示例最大值
                    const randomLong = Math.floor(Math.random() * (max - min + 1) + min);
                    var longString = randomLong.toString();
                    $('#materialsCode').val(longString);
                });
            });
            // 删除物料按钮点击事件
            $(document).on('click', '.deleteMaterialButton', function () {
                var $tr = $(this).closest('tr');
                layer.confirm('确定删除该物料吗？', function (index) {
                    $tr.remove();
                    // 重新编号
                    $('#materialTable tbody tr').each(function (index) {
                        $(this).find('td:first').text(index + 1);
                    });
                });
            });



            // 保存功能 - 修正数据结构
            $('#saveButton').click(function () {
                const id = getQueryParam('id');
                if (!id) {
                    layer.msg('无效单据ID', { icon: 2 });
                    return;
                }

                // 收集主数据
                const mainData = {
                    invoiceSettlementEntityId: parseInt(id),
                    documentCode: $('#documentCode').val(),
                    businessType: $('#businessType').val(),
                    customerName: $('#customerName').val(),
                    bank: $('#bank').val(),
                    deliveryEmail: $('#deliveryEmail').val(),
                    documentDate: $('#documentDate').val(),
                    operator: $('#operator').val(),
                    invoiceTypeFlag: $('#invoiceTypeFlag').val(),
                    accountNumber: $('#accountNumber').val(),
                    remark: $('#remark').val(),
                    documentStatus: $('#documentStatus').val(),
                    auditor: $('#auditor').val(),
                    taxRate: $('#taxRate').val(),
                    taxNumber: $('#taxNumber').val(),
                    businessStatus: $('#businessStatus').val(),
                    auditDate: $('#auditDate').val(),
                    invoiceType: $('#invoiceType').val(),
                    addressPhone: $('#addressPhone').val(),
                    orderMaterials: []
                };

                // 收集物料数据
                $('#materialTable tbody tr').each(function () {
                    const $tr = $(this);
                    mainData.orderMaterials.push({
                        materialsCode: $tr.find('.materialsCode').val(),
                        materialsName: $tr.find('.materialsName').val(),
                        modelSpecification: $tr.find('.modelSpecification').val(),
                        calulate: $tr.find('.calulate').val(),
                        calulateNumber: parseFloat($tr.find('.calulateNumber').val()) || 0,
                        price: parseFloat($tr.find('.price').val()) || 0,
                        totalPrice: parseFloat($tr.find('.totalPrice').val()) || 0,
                        qualityRequir: $tr.find('.qualityRequir').val(),
                        packRequir: $tr.find('.packRequir').val(),
                        remark: $tr.find('.remark').val(),
                        materialsClass: 6
                    });
                });

                if (mainData.orderMaterials.length === 0) {
                    layer.msg('请至少添加一个物料', { icon: 2 });
                    return;
                }

                const loadIndex = layer.load(2, { shade: 0.3 });
                $.ajax({
                    // url: 'http://localhost:5090/api/Procurements/UdpInvoiceSettlementEntityAll',
                    url: "@ViewBag.BaseUrl/T8/Procurements/UdpInvoiceSettlementEntityAll",
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(mainData),
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.code === 206) {
                            layer.msg('修改成功', { icon: 1 }, () => {
                                location.href = "/Procurements/GetInvoiceSettlementEntity";
                            });
                        } else {
                            layer.msg(res.msg || '修改失败', { icon: 2 });
                        }
                    },
                    error: function (xhr) {
                        layer.close(loadIndex);
                        const errorMsg = xhr.responseJSON?.message || xhr.statusText;
                        layer.msg(`保存失败: ${errorMsg}`, { icon: 2 });
                        console.error('错误详情:', {
                            request: mainData,
                            response: xhr.responseJSON
                        });
                    }
                });
            });

            // 计算金额
            $(document).on('change', '.calulateNumber, .price', function () {
                var $tr = $(this).closest('tr');
                var quantity = parseFloat($tr.find('.calulateNumber').val()) || 0;
                var price = parseFloat($tr.find('.price').val()) || 0;
                var total = quantity * price;
                $tr.find('.totalPrice').val(total.toFixed(2));
            });

            // 表单验证
            form.verify({
                required: function (value, item) {
                    if (value === '') {
                        return '此项不能为空';
                    }
                },
                number: function (value, item) {
                    if (value === '' || isNaN(value)) {
                        return '请输入有效的数字';
                    }
                }
            });
        });
    </script>
</body>
</html>